"use strict"

const fetch = require('node-fetch')
const cheerio = require('cheerio')
const await_for = require('./run').await_for
const _ = require('lodash/fp')

const e = raw => raw.replace(/([\\'"])/gm, '\\$1')
const e_url = raw => raw//.replace(/(https:\/\/)/gm, 'http://')
const opt = {
    timeout: 20000,
}

module.exports = [
    {
        iterator: function* () {
            const url = 'http://www.panda.tv/live_lists'
            const limit = 120
            let page = 1
            let page_count = 0

            const format = (data) => {
                if (page_count === 0) {
                    page_count = Math.ceil(data.data.total / limit)
                }
                return data.data.items.map(i => ({
                    live_id: 1,
                    room_name: e(i.name),
                    id: 'p_' + i.userinfo.rid,
                    room_id: i.id,
                    name: e(i.userinfo.nickName),
                    online: i.person_num,
                    cover: e_url(i.pictures.img),
                    avatar: e_url(i.userinfo.avatar),
                    url: `http://www.panda.tv/${i.id}`,
                    category_name: i.classification.cname,
                    category_url: "http://www.panda.tv/cate/" + i.classification.ename,
                    category_id: i.classification.ename
                }))
            }

            while (1) {
                if (page_count && page > page_count) return
                yield fetch(`${url}?pageno=${page++}&pagenum=${limit}&order=person_num&status=2`, opt)
                    .then(_ => _.json())
                    .then(format)
            }
        },

        run: 'normal'
    },

    {
        iterator: function* () {
            const url = 'http://open.douyucdn.cn/api/RoomApi/live'
            const limit = 100
            let page = 0
            let done = false

            const format = result => {
                const data = result.data
                if (data.length === 0) return done = true

                return data.map(i => ({
                    live_id: 2,
                    name: e(i.nickname),
                    room_name: e(i.room_name),
                    room_id: i.room_id,
                    online: i.online,
                    id: 'd_' + i.owner_uid,
                    url: i.url,
                    cover: e_url(i.room_src),
                    avatar: e_url(i.avatar),
                    category_id: i.cate_id,
                    category_name: i.game_name,
                    category_url: i.game_url
                }))
            }

            while (!done)
                yield fetch(`${url}?offset=${page++ * 100}&limit=${limit}`, opt)
                    .then(_ => _.json())
                    .then(format)
        },
        run: 'normal'
    },

    {
        iterator: function* () {
            const url = 'http://www.quanmin.tv/json/play/list'
            let page = 0
            let page_count = 0

            const format = result => {
                if (page_count === 0) page_count = result.pageCount

                return result.data.map(i => ({
                    live_id: 3,
                    name: e(i.nick),
                    room_name: e(i.title),
                    room_id: i.uid,
                    online: i.view,
                    id: 'q_' + i.uid,
                    url: `http://www.quanmin.tv/v/${i.slug ? i.slug : i.uid}`,
                    cover: e_url(i.thumb),
                    avatar: e_url(i.avatar),
                    category_id: i.category_id,
                    category_name: i.category_name,
                    category_url: `http://www.quanmin.tv/game/${i.category_slug}`
                }))
            }

            while (!page_count || page < page_count) {
                yield fetch(`${url}${page++ ? `_${page}` : ''}.json`, opt)
                    .then(_ => _.json())
                    .then(format)
            }
        },
        run: 'normal'
    },

    {
        iterator: function* () {
            // 战旗TV url格式：http://www.zhanqi.tv/api/static/v2.1/live/list/{$limit}/{$page}.json
            //https://apis.zhanqi.tv/static/v2.1/room/154601.json
            const url = "http://www.zhanqi.tv/api/static/v2.1/live/list"
            const limit = 100
            let page = 1
            let page_count = 0


            const format = result => {
                if (page_count === 0) page_count = Math.ceil(result.data.cnt / limit)

                return result.data.rooms.map(i => ({
                    live_id: 4,
                    name: e(i.nickname),
                    room_name: e(i.title),
                    room_id: i.id,
                    online: i.online,
                    id: 'zhanqi_' + i.uid,
                    url: `http://www.zhanqi.tv${i.url}`,
                    cover: e_url(i.bpic),
                    avatar: e_url(i.avatar) + '-big',
                    category_id: i.gameId,
                    category_name: i.gameName,
                    category_url: `${url}${i.gameUrl}`
                }))
            }

            while (!page_count || page < page_count) {
                yield fetch(`${url}/${limit}/${page++}.json`, opt)
                    .then(_ => _.json())
                    .then(format)
            }

        },
        run: 'normal'
    },

    {
        iterator: function* () {
            //龙珠TV url格式：http://api.plu.cn/tga/streams?max-results=${limit}&start-index=${offset}&sort-by=views&game=0
            // max_limit = 50

            const url = "http://api.plu.cn/tga/streams?sort-by=views&game=0"
            const limit = 50
            let page = 0
            let page_count = 0

            const format = result => {
                if (page_count === 0) page_count = Math.ceil(result.data.totalItems / limit)

                return result.data.items.map(i => ({
                    live_id: 5,
                    name: e(i.channel.name),
                    room_name: e(i.channel.status),
                    room_id: i.channel.id,
                    online: i.viewers,
                    id: 'longzhu_' + i.channel.id,
                    url: i.channel.url,
                    cover: e_url(i.preview),
                    avatar: e_url(i.channel.avatar),
                    category_id: i.game[0].id,
                    category_name: i.game[0].name,
                    category_url: `http://longzhu.com/channels/${i.game[0].tag}`
                }))
            }

            while (!page_count || page < page_count) {
                yield fetch(`${url}&max-results=${limit}&start-index=${page++ * limit}`, opt)
                    .then(_ => _.json())
                    .then(format)
            }
        },
        run: 'normal'
    },

    {
        iterator: function* () {
            //虎牙TV url格式：http://www.huya.com/cache.php?m=Live&do=ajaxAllLiveByPage&page=${page}
            //虎牙只能一次获取20条数据, 只抓取前1000条数据
            const url = "http://www.huya.com/cache.php?m=Live&do=ajaxAllLiveByPage&page="
            const page_count = 51
            let page = 1

            const format = result => {

                return result.data.list.map(i => ({
                    live_id: 6,
                    name: e(i.nick),
                    room_name: e(i.introduction),
                    room_id: i.privateHost,
                    online: i.totalCount,
                    id: 'huya_' + i.uid,
                    url: `http://www.huya.com/${i.privateHost}`,
                    cover: e_url(i.screenshot),
                    avatar: e_url(i.avatar180),
                    category_id: i.gid,
                    category_name: i.gameFullName,
                    category_url: `http://www.huya.com/g/${i.gameHostName ? i.gameHostName : i.gid}`
                }))
            }

            while (!page_count || page < page_count) {
                yield fetch(`${url}${page++}`, opt)
                    .then(_ => _.json())
                    .then(format)
            }
        },
        run: 'normal'
    },

    {
        run: function () {
            //繁星 url格式 http://visitor.fanxing.kugou.com/VServices/IndexService.IndexService.getAreaHotLiveRoomAllByType/0-0-0/

            const url = "http://visitor.fanxing.kugou.com/VServices/IndexService.IndexService.getAreaHotLiveRoomAllByType/0-0-0/"

            const format = result => {
                const list = (result.data.list && result.data.list.map) ? result.data.list : result.data

                return list.filter ? list
                    .filter(i => i.status == 1)
                    .map(i => {
                        const cate = i.starTagsList[0] == undefined ? { starTagsId: "20", starTagsName: "青春偶像" } : i.starTagsList[0]
                        return {
                            live_id: 7
                            , name: e(i.nickName)
                            , room_name: e(i.nickName)
                            , online: i.viewerNum
                            , id: 'fx_' + i.userId
                            , room_id: i.roomId
                            , url: `http://fanxing.kugou.com/${i.roomId}`
                            , cover: e_url(i.imgPath)
                            , avatar: e_url(i.imgPath)
                            , category_id: cate.starTagsId
                            , category_name: cate.starTagsName
                            , category_url: `http://fanxing.kugou.com/`
                        }
                    }) : []
            }

            return Promise.all(
                [
                    "http://visitor.fanxing.kugou.com/VServices/IndexService.IndexService.getAreaHotLiveRoomAllByType/0-0-0/",
                    "http://visitor.fanxing.kugou.com/VServices/IndexService.IndexService.getHotStarList/",
                    "http://visitor.fanxing.kugou.com/VServices/IndexService.IndexService.getNewerStarList/",
                ].map(url => fetch(`${url}`, { timeout: 60000 })
                    .then(_ => _.text())
                    .then(_ => _.slice(_.indexOf('{'), _.lastIndexOf('}') + 1))
                    .then(JSON.parse)
                    .then(format)
                    ))
                .then(_.flattenDeep)
                .then(_.uniqBy('id'))
        }
    },

    {
        iterator: function* () {
            //来疯 url格式： http://www.laifeng.com/center?pageNo=${page}

            const url = `http://www.laifeng.com/center?pageNo=`;
            let page = 1
            const page_count = 11

            const format = result => {
                let $ = cheerio.load(result)
                let data = [];

                $('ul.user-list li:has(i.online)').map((i, t) => data.push(
                    {
                        live_id: 8
                        , name: e($(t).find('p.name a').text())
                        , room_name: e($(t).find('p.name a').text())
                        , online: isNaN(parseInt($(t).find('p.data').text().split('\n')[2])) ? 0 : parseInt($(t).find('p.data').text().split('\n')[2])
                        , id: 'laifeng_' + $(t).find('p.name a').attr('href').replace(/[^\d]+/, '')
                        , room_id: $(t).find('p.name a').attr('href').replace(/[^\d]+/, '')
                        , url: $(t).find('p.name a').attr('href')
                        , cover: $(t).find('p.pic img').attr('src')
                        , avatar: $(t).find('p.pic img').attr('src')
                        , category_id: 1
                        , category_name: '来疯直播'
                        , category_url: `http://www.laifeng.com`
                    }))

                return data
            }

            while (page_count > page) {
                yield fetch(`${url}${page++}`, opt)
                    .then(_ => _.text())
                    .then(format)
            }
        },

        run: 'normal'
    },

    require('./huajiao'),

    {
        iterator: function* () {
            //bilibili http://live.bilibili.com/area/liveList?area=all&order=online&page=${page}
            const url = 'http://live.bilibili.com/area/liveList?area=all&order=online&page='
            let page = 1
            let done = false

            const format = result => {
                const data = result.data
                if (!data || data.length === 0) return done = true

                return data.map(i => ({
                    live_id: 10,
                    name: e(i.uname),
                    room_name: e(i.title),
                    room_id: i.roomid,
                    online: i.online,
                    id: 'b_' + i.uid,
                    url: `http://live.bilibili.com${i.link}`,
                    cover: e_url(i.system_cover),
                    avatar: e_url(i.face),
                    category_id: i.area,
                    category_name: i.areaName,
                    category_url: 'do not konw'
                }))
            }

            while (!done)
                yield fetch(`${url}${page++}`, opt)
                    .then(_ => _.json())
                    .then(format)
        },

        run: 'normal'
    },

    {
        iterator: function* () {
            //网易cc http://cc.163.com/category/live/?format=json&start=${offset}&size=${limit}
            //swf http://service.hi.163.com/static/v/CCMediaPlayer.swf?v=0.3.9&geturl=1&maskinterval=30&secret=None&defaultip=114.113.200.201&file=${ccid}&provider=rhttp&debug=true&groupcgihost=group.v.cc.163.com&autoplay=true
            const url = 'http://cc.163.com/category/live/?format=json&'
            let page = 0
            const limit = 100
            let done = false

            const format = result => {
                const data = result.lives
                if (!data || data.length === 0) return done = true

                return data.map(i => ({
                    live_id: 11,
                    name: e(i.nickname),
                    room_name: e(i.title),
                    room_id: i.ccid,
                    online: i.webcc_visitor,
                    id: 'cc_' + i.uid,
                    url: `http://cc.163.com/${i.ccid}`,
                    cover: e_url(i.cover),
                    avatar: e_url(i.purl),
                    category_id: i.gametype,
                    category_name: i.gamename,
                    category_url: `http://cc.163.com/category/list/?gametype=${i.gametype}`
                }))
            }

            while (!done)
                yield fetch(`${url}start=${page++ * limit}&size=${limit}`, opt)
                    .then(_ => _.json())
                    .then(format)
        },

        run: 'normal'
    },

    {
        // 6房间
        run: () =>
            fetch("http://www.6.cn/liveAjax.html", { timeout: 60000 })
                .then(_ => _.json())
                .then(_ => _.roomList.map(i => ({
                    live_id: 12,
                    name: e(i.username),
                    room_name: e(i.username),
                    room_id: i.rid,
                    online: i.count,
                    id: '6_' + i.uid,
                    url: `http://v.6.cn/${i.rid}`,
                    cover: e_url(i.pic),
                    avatar: e_url(i.pic),
                    category_id: i.rtype.replace(/r\d+/, 'r1'),
                    category_name: '',
                    category_url: `http://v.6.cn/`
                })))
    },

    {
        //触手tv
        run: () => {
            const url = "http://chushou.tv/live/down-v2.htm?breakpoint="
            let bp = ''
            let done = false
            let page = 0

            const iter = function* () {
                const format = result => {
                    const data = result.data.items
                    if (!data || data.length === 0) return done = true

                    bp = result.data.breakpoint

                    return data.map(i => ({
                        live_id: 13,
                        name: e(i.meta.creator),
                        room_name: e(i.name),
                        room_id: i.targetKey,
                        online: i.meta.onlineCount,
                        id: 'chushou_' + i.targetKey,
                        url: `http://chushou.tv/room/${i.targetKey}.htm`,
                        cover: e_url(i.cover),
                        avatar: e_url(i.meta.avatar),
                        category_id: i.meta.gameCtxPath,
                        category_name: i.meta.gameName,
                        category_url: `http://chushou.tv/gamezone/${i.meta.gameCtxPath}.htm`
                    }))
                }

                while (!done && page++ < 20)
                    yield fetch(`${url}${bp}`, opt)
                        .then(_ => _.json())
                        .then(format)
            }

            return await_for(iter()).then(_.flattenDeep).then(_.uniqBy('id'))
        }
    },

    {
        //一直播
        iterator: function* () {
            const url = 'http://yizhibo.com/www/web/get_hot_list'
            const limit = 63
            let page = 0
            let done = false

            const format = result => {
                const data = result.data.list
                if (data.length === 0 || result.data.is_finished === 1) return done = true

                return data.map(i => ({
                    live_id: 14,
                    name: e('' + i.nickname),
                    room_name: e(i.title),
                    room_id: i.scid,
                    online: i.online,
                    id: 'yizhibo_' + i.memberid,
                    url: i.liveurl,
                    cover: e_url(i.cover),
                    avatar: e_url(i.avatar),
                    category_id: i.ytypename,
                    category_name: i.ytypename,
                    category_url: 'not konw'
                }))
            }

            while (!done)
                yield fetch(`${url}?start=${page++ * limit}&limit=${limit}`, opt)
                    .then(_ => _.json())
                    .then(format)
        },

        run: 'normal'
    },

    //yy
    require('./yy'),

    {
        //章鱼
        iterator: function* () {
            const url = 'http://www.zhangyu.tv/channel/getchannels'//?s=0&n=100
            const limit = 100
            let page = 0
            let done = false

            const format = result => {
                if (result.length === 0) return done = true

                return result.map(i => ({
                    live_id: 16,
                    name: e('' + i.uname),
                    room_name: e(i.cname),
                    room_id: i._id,
                    online: i.online,
                    id: 'zhangyu_' + i._id,
                    url: `http://www.zhangyu.tv/${i.url}`,
                    cover: e_url(i.imageUrl),
                    avatar: e_url(i.figurl),
                    category_id: 1,
                    category_name: '体育',
                    category_url: 'not konw'
                }))
            }

            while (!done)
                yield fetch(`${url}?s=${page++ * limit}&n=${limit}`, opt)
                    .then(_ => _.json())
                    .then(format)
        },

        run: 'normal'
    }
]